package com.teamwings.ctrls.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teamwings.common.exception.ResultException;
import com.teamwings.common.vo.Result;
import com.teamwings.ctrls.service.IUploadService;
import com.teamwings.modules.oss.entity.OssFile;
import com.teamwings.modules.oss.service.IOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "文件上传组件管理")
@RequestMapping("/form/ctrl")
public class UploadController {

    // 对象存储服务
    @Autowired
    private IOssService ossService;

    // 基于存储服务的封装
    @Autowired
    private IUploadService uploadService;

    /**
     * weihc 基于minion，完成文件上传，并把相应的文件信息存储到table_form_oss_file表，但是这里不设置表单实例id
     * 2021-6-22 weihc 目前文件上传不再使用minio，而是使用信创oa的文件服务, 除了上传到其他文件服务之外，其他逻辑没有修改
     * @param formId  自定义表单id
     * @param file    上传过来的文件
     * @param bizPath 设置存储路径
     * @param fileType 文件来源类型 0、普通附件 1、办文 2、邮件 3、意见附件
     * @return Result
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "{formId}/upload/upload")
    public Result<?> upload(
            @PathVariable("formId") String formId,
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "bizPath", required = false) String bizPath,
            @RequestParam(value = "fileType", required = false) String fileType
    ) {
        OssFile ossFile = uploadService.saveToFileService(formId, null, null, file, bizPath, fileType);
        return Result.OK("文件保存成功！", ossFile);
    }

    /**
     * 完成文件上传，并把相应的文件信息存储到table_form_oss_file表(包括表单实例id)
     * 2021-6-22 weihc 目前文件上传不再使用minio，而是使用信创oa的文件服务, 除了上传到其他文件服务之外，其他逻辑没有修改
     * @param tableId  表单实例id
     * @param formId  自定义表单id
     * @param file    上传过来的文件
     * @param bizPath 设置存储路径
     * @param fileType 附件来源类型 0、普通附件 1、办文 2、邮件 3、意见附件
     * @return Result
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "{formId}/upload/{tableId}/upload")
    public Result<?> uploadAndLogic(
            @PathVariable("formId") String formId,
            @PathVariable(value = "tableId") String tableId,
            @RequestParam(value = "uploadList", required = false) String uploadList,
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "bizPath",required = false) String bizPath,
            @RequestParam(value = "fileType", required = false) String fileType
    ) {
        OssFile ossFile = uploadService.saveToFileService(formId, tableId, uploadList, file, bizPath, fileType);
        return Result.OK("文件保存成功！", ossFile);
    }

//    @ApiOperation(value = "上传文件列表后保存文件列表信息", notes = "上传文件列表后保存文件列表信息")
//    @PostMapping(value = "/{formId}/upload/{tableId}/saveBatch")
//    public Result<?> saveBatch(
//            @PathVariable("formId") String formId,
//            @PathVariable(value = "tableId") String tableId,
//            @RequestParam(value = "ossFileList") List<OssFile> ossFileList
//    ) {
//        ossService.saveBatch(ossFileList);
//        ossFileList.forEach(entity -> {
//            entity.setFormId(formId);
//            entity.setTableId(tableId);
//        });
//        return Result.OK("文件保存成功！");
//    }

    @ApiOperation(value = "获取对应的文件列表", notes = "获取对应的文件列表")
    @GetMapping(value = "/{formId}/upload/{tableId}/list")
    public Result<?> list(
            @PathVariable("formId") String formId,
            @PathVariable(value = "tableId") String tableId,
            @RequestParam(value = "uploadList", required = false) String uploadList
    ) {
        LambdaQueryWrapper<OssFile> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(formId)) {
            queryWrapper.eq(OssFile::getFormId, formId);
        }
        if (StringUtils.isNotEmpty(tableId)) {
            queryWrapper.eq(OssFile::getTableId, tableId);
        }
        if (StringUtils.isNotEmpty(uploadList)) {
            queryWrapper.eq(OssFile::getUploadList, uploadList);
        }
        List<OssFile> list = ossService.list(queryWrapper);
        return Result.OK("文件列表获取成功！", list);
    }

    @ApiOperation(value = "下载文件", notes = "下载文件")
    @PostMapping(value = "/{formId}/upload/{tableId}/download/{fileId}")
    public void download(
            HttpServletResponse response,
            @PathVariable(value = "formId", required = false) String formId,
            @PathVariable(value = "tableId", required = false) String tableId,
            @PathVariable(value = "fileId", required = false) String fileId
    ) {
        LambdaQueryWrapper<OssFile> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotEmpty(formId)) {
            queryWrapper.eq(OssFile::getFormId, formId);
        }

        if (StringUtils.isNotEmpty(tableId)) {
            queryWrapper.eq(OssFile::getTableId, tableId);
        }

        if (StringUtils.isNotEmpty(fileId)) {
            if (fileId.contains(",")) {
                queryWrapper.in(OssFile::getId, Arrays.asList(fileId.split(",")));
            } else {
                queryWrapper.eq(OssFile::getId, fileId);
            }
        }
        List<OssFile> ossFileList = ossService.list(queryWrapper);

        if (ossFileList == null || ossFileList.size() == 0) {
            throw new ResultException("没有找到对应文件");
        }

        List<String> pathList = ossFileList.stream().map(OssFile::getFilePath).collect(Collectors.toList());
// minio 下载文件夹代码
//        if (pathList.size() == 1) {
//            ossService.downloadFile(pathList.get(0), response);
//        } else {
//            ossService.downloadFiles(pathList, response);
//        }

        // 文件服务下载文件代码
        if (pathList.size() == 1) {
            uploadService.downloadFile(pathList.get(0), response);
        } else {
            List<String> paths = new ArrayList<>();
            List<String> filenames = new ArrayList<>();
            ossFileList.forEach(ossFile -> {
                paths.add(ossFile.getFilePath());
                filenames.add(ossFile.getFileName());
            });
            uploadService.downloadFiles(StringUtils.join(paths, ","), StringUtils.join(filenames, ","), response);
        }
    }

    @ApiOperation(value = "删除文件", notes = "删除文件")
    @DeleteMapping(value = "/{formId}/upload/{tableId}/remove/{fileId}")
    public Result<?> remove(
            @PathVariable("formId") String formId,
            @PathVariable(value = "tableId") String tableId,
            @PathVariable(value = "fileId", required = false) String fileId
    ) {
        LambdaQueryWrapper<OssFile> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(formId)) {
            queryWrapper.eq(OssFile::getFormId, formId);
        }
        if (StringUtils.isNotEmpty(tableId)) {
            queryWrapper.eq(OssFile::getTableId, tableId);
        }
        if (StringUtils.isNotEmpty(fileId)) {
            queryWrapper.eq(OssFile::getId, fileId);
        }
        ossService.remove(queryWrapper);
        return Result.OK("文件删除成功！");
    }

}
